<template>
  <div class="card">
    <div style="display: block">
      <a href="#" target="_blank">
        <el-image src="/vite.svg" class="logo" alt="Vite logo" />
      </a>
      <a href="#" target="_blank">
        <img src="../../assets/vue.svg" class="logo vue" alt="Vue logo" />
      </a>
    </div>
    <el-form label-width="auto">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="loginInfo.username" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="loginInfo.password" placeholder="请输入密码" type="password"></el-input>
      </el-form-item>
      <el-form-item label="验证码" prop="captchaCode">
        <el-input v-model="loginInfo.captchaKey" hidden></el-input>
        <el-input v-model="loginInfo.captchaCode" placeholder="请输入验证码"></el-input>
        <el-image :src="captcha.captchaBase64" alt="验证码" @click="captchaRequest"></el-image>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="login">登录</el-button>
        <el-button @click="getToken">token</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script lang="ts" setup>

import { reactive,onMounted } from 'vue'
import { getCaptchaApi,loginApi } from '../../api/auth'
import { useAuthStore} from '../../utils/store'
import { useRouter } from 'vue-router';

const captcha = reactive({captchaBase64:'',captchaKey:''});
const loginInfo = reactive({username:'',password:'',captchaCode:'',captchaKey:''})
const authStore = useAuthStore()
const router = useRouter()


function captchaRequest(){
  getCaptchaApi().then(res => {
    Object.assign(captcha, res.data)
  })
}

function login(){
  loginInfo.captchaKey = captcha.captchaKey
  loginApi(loginInfo).then(res => {
    let {code} = res as any;
    let {accessToken} = res.data
    console.log(accessToken)
    authStore.setToken(accessToken)
    if(code == '00000'){
      router.push({path:'/'})
    }
  }).catch(err=>{
    console.log("Login.vue 登录失败")
    console.log(err.response.data.msg)
    alert(err.response.data.msg)
  })
}

function getToken(){
  let token = authStore.token;
  alert(token)
}

onMounted(() => {
  captchaRequest()
})
</script>
<style scoped>
.logo {
  height: 6em;
  padding: 1.5em;
  will-change: filter;
  transition: filter 300ms;
}
.logo:hover {
  filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.vue:hover {
  filter: drop-shadow(0 0 2em #42b883aa);
}

.card {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
  background-color: #f8f6f6;
  padding: 2em;
  border-radius: 10px;
  width: 400px;
  margin: 0 auto;
  margin-top: 200px;
}
</style>